package com.zdya.combatdocuments.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.zdya.combatdocuments.entity.vo.XLSMindMapVO;
import com.zdya.combatdocuments.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;

import java.net.URLEncoder;
import java.util.List;

/**
 * * @author: bj
 * * @date: 2023/6/14
 * * @desc:
 */
@Slf4j
public class ExcelUtil {

    public static void writeExcelOneSheet(HttpServletResponse response, String fileName, String sheet, List<XLSMindMapVO> data) {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String name = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename=" + name + ".xlsx");
            EasyExcel.write(response.getOutputStream(), XLSMindMapVO.class).sheet(sheet).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).doWrite(data);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException("导出失败！");
        }
    }
}
